<!DOCTYPE html>
<html>
<head>
    <title>客服聊天记录</title>
    {% include 'system/common/header.html' %}
    <style>
        .chat-stats-card {
            text-align: center;
            padding: 20px;
        }
        .chat-stats-card h3 {
            font-size: 24px;
            color: #1E9FFF;
            margin-bottom: 5px;
        }
        .chat-stats-card p {
            color: #666;
            margin: 0;
        }
        .chat-message-item {
            margin-bottom: 15px;
        }
        .chat-message-bubble {
            max-width: 80%;
            padding: 10px 15px;
            border-radius: 15px;
            word-wrap: break-word;
        }
        .chat-message-user {
            text-align: right;
        }
        .chat-message-user .chat-message-bubble {
            background: #1E9FFF;
            color: white;
            margin-left: auto;
        }
        .chat-message-assistant {
            text-align: left;
        }
        .chat-message-assistant .chat-message-bubble {
            background: white;
            color: #333;
            border: 1px solid #e0e0e0;
        }
    </style>
</head>
<body class="ppress-container">
<div class="layui-card">
    <div class="layui-card-header">
        <span class="layui-badge layui-bg-blue">客服聊天记录</span>
    </div>
    <div class="layui-card-body">
        <!-- 统计信息 -->
        <div class="layui-row layui-col-space15" style="margin-bottom: 20px;">
            <div class="layui-col-md2">
                <div class="layui-card">
                    <div class="layui-card-body chat-stats-card">
                        <h3 id="todaySessions">0</h3>
                        <p>今日会话</p>
                    </div>
                </div>
            </div>
            <div class="layui-col-md2">
                <div class="layui-card">
                    <div class="layui-card-body chat-stats-card">
                        <h3 id="totalSessions">0</h3>
                        <p>总会话</p>
                    </div>
                </div>
            </div>
            <div class="layui-col-md2">
                <div class="layui-card">
                    <div class="layui-card-body chat-stats-card">
                        <h3 id="activeSessions">0</h3>
                        <p>活跃会话</p>
                    </div>
                </div>
            </div>
            <div class="layui-col-md2">
                <div class="layui-card">
                    <div class="layui-card-body chat-stats-card">
                        <h3 id="todayMessages">0</h3>
                        <p>今日消息</p>
                    </div>
                </div>
            </div>
            <div class="layui-col-md2">
                <div class="layui-card">
                    <div class="layui-card-body chat-stats-card">
                        <h3 id="totalMessages">0</h3>
                        <p>总消息</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 搜索区域 -->
        <form class="layui-form layui-form-pane" lay-filter="searchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">用户姓名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="user_name" placeholder="请输入用户姓名" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">用户电话</label>
                    <div class="layui-input-inline">
                        <input type="text" name="user_phone" placeholder="请输入用户电话" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">会话状态</label>
                    <div class="layui-input-inline">
                        <select name="status">
                            <option value="">全部状态</option>
                            <option value="active">活跃</option>
                            <option value="closed">已关闭</option>
                            <option value="timeout">超时</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn" lay-submit lay-filter="search">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>

        <!-- 会话列表 -->
        <table id="sessionTable" lay-filter="sessionTable"></table>
    </div>
</div>

<!-- 聊天记录详情模态框 -->
<div id="chatDetailModal" style="display: none; padding: 20px;">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3 id="sessionTitle">聊天记录详情</h3>
        </div>
        <div class="layui-card-body">
            <div id="chatMessages" style="height: 400px; overflow-y: auto; border: 1px solid #e6e6e6; padding: 10px; background: #f8f9fa;">
                <!-- 聊天记录将在这里显示 -->
            </div>
        </div>
    </div>
</div>

<!-- 表格工具栏 -->
<script type="text/html" id="sessionTableBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">查看记录</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
</script>

<!-- 会话状态模板 -->
<script type="text/html" id="sessionStatusTpl">
{% raw %}
    {{# if(d.status === 'active'){ }}
        <span class="layui-badge layui-bg-green">活跃</span>
    {{# } else if(d.status === 'closed'){ }}
        <span class="layui-badge layui-bg-gray">已关闭</span>
    {{# } else if(d.status === 'timeout'){ }}
        <span class="layui-badge layui-bg-orange">超时</span>
    {{# } }}
{% endraw %}
</script>
</body>
{% include 'system/common/footer.html' %}

<script>
layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.jquery;

    // 加载统计信息
    function loadStats() {
        $.get('/admin/cms/chat/io/stats', function(res) {
            if (res.success === true) {
                $('#todaySessions').text(res.data.today_sessions);
                $('#totalSessions').text(res.data.total_sessions);
                $('#activeSessions').text(res.data.active_sessions);
                $('#todayMessages').text(res.data.today_messages);
                $('#totalMessages').text(res.data.total_messages);
            }
        });
    }

    // 初始化统计信息
    loadStats();

    // 会话列表表格
    var sessionTable = table.render({
        elem: '#sessionTable',
        url: '/admin/cms/chat/io/sessions',
        page: true,
        cols: [[
            {field: 'session_id', title: '会话ID', width: 200},
            {field: 'user_name', title: '用户姓名', width: 120},
            {field: 'user_phone', title: '用户电话', width: 150},
            {field: 'ip_address', title: 'IP地址', width: 120},
            {field: 'status', title: '状态', width: 100, templet: '#sessionStatusTpl'},
            {field: 'message_count', title: '消息数', width: 100},
            {field: 'start_time', title: '开始时间', width: 180},
            {field: 'end_time', title: '结束时间', width: 180},
            {title: '操作', width: 150, toolbar: '#sessionTableBar', fixed: 'right'}
        ]],
        done: function() {
            // 表格渲染完成后的回调
        }
    });

    // 搜索表单提交
    form.on('submit(search)', function(data) {
        sessionTable.reload({
            where: data.field,
            page: {curr: 1}
        });
        return false;
    });

    // 表格工具栏事件
    table.on('tool(sessionTable)', function(obj) {
        var data = obj.data;
        if (obj.event === 'detail') {
            showChatDetail(data.session_id);
        } else if (obj.event === 'delete') {
            deleteSession(data.session_id);
        }
    });

    // 显示聊天记录详情
    function showChatDetail(sessionId) {
        // 获取会话详情
        $.get('/admin/cms/chat/io/session/' + sessionId, function(res) {
            console.info( "res:"+res)
            console.info( "res.success:"+res.success)
            if (res.success === true) {
                var session = res.data;
                $('#sessionTitle').text('聊天记录 - ' + (session.user_name || '匿名用户'));
                
                // 获取聊天记录
                $.get('/admin/cms/chat/io/records/' + sessionId, function(recordRes) {
                    if (recordRes.code === 0) {
                        console.info( "recordRes:"+recordRes)
                        renderChatMessages(recordRes.data);
                    }
                });
            }
        });

        layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            shadeClose: true,
            area: ['800px', '600px'],
            content: $('#chatDetailModal')
        });
    }

    // 渲染聊天消息
    function renderChatMessages(messages) {
        var html = '';
        messages.forEach(function(msg) {
            var messageClass = msg.sender_type === 'user' ? 'chat-message-user' : 'chat-message-assistant';
            var time = new Date(msg.create_time).toLocaleString();
            
            html += `
                <div class="chat-message-item ${messageClass}">
                    <div style="font-size: 12px; color: #999; margin-bottom: 5px;">
                        ${msg.sender_type === 'user' ? '用户' : '客服'} - ${time}
                    </div>
                    <div class="chat-message-bubble">
                        ${msg.content}
                    </div>
                </div>
            `;
        });
        
        $('#chatMessages').html(html);
        $('#chatMessages').scrollTop($('#chatMessages')[0].scrollHeight);
    }

    // 删除会话
    function deleteSession(sessionId) {
        layer.confirm('确定要删除这个会话吗？删除后将无法恢复！', {
            icon: 3,
            title: '确认删除'
        }, function(index) {
            $.ajax({
                url: '/admin/cms/chat/io/session/' + sessionId,
                type: 'DELETE',
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg('删除成功', {icon: 1});
                        sessionTable.reload();
                        loadStats(); // 重新加载统计信息
                    } else {
                        layer.msg(res.msg || '删除失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('删除失败', {icon: 2});
                }
            });
            layer.close(index);
        });
    }
});
</script>